const httpclient = require('../../utils/httpclient.js')
const md5Util = require('../../utils/md5.js')
const util = require('../../utils/util.js')

//获取应用实例
var app = getApp()

Page({
  data: {
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    hasNoCoupons: true,
    coupons: [],
    youhuijine: 0, //优惠券金额
    multiArray: [[], []],
    multiIndex: [0, 0],
    serviceTime: '',
    serviceDate: '',
    curCoupon: null, // 当前选择使用的优惠券,
    days: ['日','一', '二', '三', '四', '五', '六'],
    dates:[]
  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    // 选择的数据信息必须两个都不能为空
    if (this.data.multiArray[1].length > 0){
      this.setData({
        serviceTime: this.data.multiArray[0][e.detail.value[0]] + this.data.multiArray[1][e.detail.value[1]],
        serviceDate: this.data.dates[e.detail.value[0]] + ' ' + this.data.multiArray[1][e.detail.value[1]]
      });
    }else{
      wx.showModal({
        title: '错误',
        content: '请选择一个有具体送达时间的日期!',
        showCancel: false
      })
      return;
    }
  },
  bindMultiPickerColumnChange: function (e) {
    var that = this;
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let useTimes = [];
    if (e.detail.column == 0) {
      switch (e.detail.value) {
        case 0:
          // 计算当前时间可以选取的送外卖时间
          var now = new Date();
          // 检查离最近个位为0的时间差多少分钟
          var timeDiffMin = now.getMinutes() - (parseInt(now.getMinutes() / 10) * 10);
          now.setTime(now.getTime() - timeDiffMin * 60 * 1000);
          now.setTime(now.getTime() + 20 * 60 * 1000);
          while (now.getHours() < 21) {
            now.setTime(now.getTime() + 20 * 60 * 1000);
            useTimes.push(now.getHours() + ':' + now.getMinutes());
          }
          var multiArray = that.data.multiArray;
          multiArray[1] = useTimes;
          that.setData({
            multiArray: multiArray
          });
          break;
        case 1:
          // 计算当前时间可以选取的送外卖时间
          var now = new Date();
          now.setHours(8);
          now.setMinutes(0);
          now.setSeconds(0);
          now.setDate(now.getDate() + 1);

          while (now.getHours() < 21) {
            now.setTime(now.getTime() + 20 * 60 * 1000);
            useTimes.push(now.getHours() + ':' + now.getMinutes());
          }
          var multiArray = that.data.multiArray;
          multiArray[1] = useTimes;
          that.setData({
            multiArray: multiArray
          });
          break;
        default:
          break;
      }
    }
  },
  onLoad: function (e) {
    var that = this;
    var multiArray = that.data.multiArray;

    // 计算当前时间可以选取的送外卖时间
    var now = new Date();
    var now_next_day = new Date();
    now_next_day.setTime(now.getTime() + 24 * 60 * 60 * 1000);
    console.log(now.getDay());
    multiArray[0] = ['今天(周' + this.data.days[now.getDay()] + ')',
      '明天(周' + this.data.days[(now.getDay()+1)%7] + ')'];

    this.setData({
      dates: [now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate(),
        now_next_day.getFullYear() + '-' + (now_next_day.getMonth() + 1) + '-' + (now_next_day.getDate())]
    });
    // 检查离最近个位为0的时间差多少分钟
    var timeDiffMin = now.getMinutes() - (parseInt(now.getMinutes() / 10) * 10);
    now.setTime(now.getTime() - timeDiffMin * 60 * 1000);
    now.setTime(now.getTime() + 20 * 60 * 1000);

    let useTimes = [];
    while (now.getHours() < 21) {
      now.setTime(now.getTime() + 20 * 60 * 1000);
      useTimes.push(now.getHours() + ':' + now.getMinutes());
    }
    multiArray[1] = useTimes;

    //显示收货地址标识
    that.setData({
      isNeedLogistics: 1,
      cart: app.globalData.cart,
      multiArray: multiArray
    });

    // 计算总计要支付的金额
    let cartTotalPrice = 0;
    that.data.cart.forEach(function (item, index) {
      cartTotalPrice += item.count * item.now_price;
    });
    that.setData({
      cartTotalPrice: cartTotalPrice
    });

    // 查看用户的默认收货信息
    httpclient.req(
      "/mall/query_user_default_consignee_info",
      {
        user_id: app.globalData.userInfo.id
      },
      'post',
      function (res) {
        if (res.data.result) {
          that.setData({
            curAddressData: res.data.consignee
          });
        }
      },
      function (result) {
        console.log(result)
      }
    );

    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  createOrder: function (e) {
    var that = this;
    var remark = e.detail.value.remark; // 备注信息

    var postData = {
      goodsJsonStr: JSON.stringify(that.data.cart),
      remark: remark,
      appid: app.globalData.appId,
      mch_id: app.globalData.mch_id,
      shop_key: app.globalData.shop_key,
      app_secret: app.globalData.appSecret
    };
    if (that.data.isNeedLogistics > 0) {
      if (!that.data.curAddressData) {
        wx.showModal({
          title: '错误',
          content: '请先设置您的收货地址！',
          showCancel: false
        })
        return;
      }
      // 收货人地址
      postData.address = that.data.curAddressData.address;
      // 收货人姓名
      postData.consignee_name = that.data.curAddressData.name;
      // 收货人电话
      postData.tel = that.data.curAddressData.tel;
      // 收货人性别
      postData.gender = that.data.curAddressData.gender;
      // 收货人楼号
      postData.no = that.data.curAddressData.no;
    }

    // 送达时间不选择不能提交
    if (!that.data.serviceDate) {
      wx.showModal({
        title: '错误',
        content: '请选择送达时间后再提交订单！',
        showCancel: false
      })
      return;
    }

    // 期望送到时间
    postData.send_time = that.data.serviceDate;
    postData.send_time_str = that.data.serviceTime;

    // 实际支付金额
    postData.pay_mo = that.data.cartTotalPrice;
    postData.platform_user_id = app.globalData.userInfo.id;

    // 查看用户的默认收货信息
    httpclient.req(
      "/mall/create_order",
      postData,
      'post',
      function (res) {
        console.log(res.data);
        if (res.data.result) {
          // 订单提交成功后再创建微信订单
          let order_id = res.data.order_id;
          let body = '';
          that.data.cart.forEach(function (item, index) {
            body += item.name + ',';
          });
          body += '商品';
          httpclient.req(
            "/api/weixin/place_order",
            {
              body: body,
              detail: '优惠购买',
              attach: '外卖版',
              order_id: order_id,
              total_fee: parseInt(that.data.cartTotalPrice * 100),
              openid: app.globalData.openid,
              appid: app.globalData.appId,
              mch_id: app.globalData.mch_id,
              shop_key: app.globalData.shop_key
            },
            'post',
            function (res) {
              console.log(res.data);
              let prepay_id = res.data.prepay_id;
              //appid
              let app_id = app.globalData.appId;
              //商户号
              let mch_id = app.globalData.mch_id;
              //时间戳
              let timestamp = (new Date()).valueOf()+'';
              //商户key
              let shop_key = app.globalData.shop_key;
              //随机字符串
              let nonceStr = util.makeRandom(10) +'';
              //签名类型
              let signType = 'MD5';
              //package
              let _package = "prepay_id=" + prepay_id;
              let content = 'appId=' + app_id + '&nonceStr=' + nonceStr + '&package=' + _package
                + '&signType=MD5&timeStamp=' + timestamp + '&key=' + shop_key;
              
              //调起微信支付
              wx.requestPayment({
                'timeStamp': timestamp,
                'nonceStr': nonceStr,
                'package': _package,
                'signType': 'MD5',
                'paySign': md5Util.md5(content),
                'success': function (res) {
                  var pages = getCurrentPages();
                  var prevPage = pages[pages.length - 2];  //上一个页面
                  let dishesList = prevPage.data.dishesList;
                  dishesList.forEach(function (dishes, index) {
                    dishes.forEach((dishe, s_index) => {
                      dishe.count = 0;
                    });
                  });
                  //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
                  prevPage.setData({
                    cart: [],
                    cartTotal: 0,
                    cartPrice: 0,
                    dishesList: dishesList
                  })
                  
                  // 跳转到餐厅首页
                  wx.navigateBack({
                    
                  });
                },
                'fail': function (res) {
                  console.log("接口调用失败的回调函数");
                  that.setData({ payFalse: false });
                }
              });
            },
            function (result) {
              console.log(result)
            }
          );
        }
      },
      function (result) {
        console.log(result)
      }
    );
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },
  getMyCoupons: function () {
    
  },
  bindChangeCoupon: function (e) {
    
  }
})
